'use client';

import { useState } from 'react';
import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form';
import * as z from 'zod';
import { Button } from '@/components/ui/button';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { useToast } from '@/components/ui/use-toast';
import { Toaster } from 'sonner';
import { User, updateUserProfile, uploadAvatar } from '@/services/userService';
import { useRouter } from 'next/navigation';

const profileFormSchema = z.object({
  name: z.string().min(2, '姓名至少2个字符'),
  email: z.string().email('请输入有效的邮箱地址').optional().or(z.literal('')),
  phone: z.string().min(11, '请输入有效的手机号码').optional().or(z.literal('')),
});

type ProfileFormValues = z.infer<typeof profileFormSchema>;

interface ProfileFormProps {
  user: User;
}

export function ProfileForm({ user }: ProfileFormProps) {
  const [isLoading, setIsLoading] = useState(false);
  const [isUploading, setIsUploading] = useState(false);
  const { toast } = useToast();
  const [previewUrl, setPreviewUrl] = useState<string | null>(user.avatar || null);
  const router = useRouter();

  const form = useForm<ProfileFormValues>({
    resolver: zodResolver(profileFormSchema),
    defaultValues: {
      name: user.name,
      email: user.email || '',
      phone: user.phone || '',
    },
  });

  // 处理认证错误的通用函数
  const handleAuthError = (error: any) => {
    if (error.isAuthError || (error.response && error.response.status === 401)) {
      toast({
        title: '登录已过期',
        description: '请重新登录后再试',
        variant: 'destructive',
      });
      
      // 延迟跳转，让用户有时间看到提示
      setTimeout(() => {
        router.push('/auth/login');
      }, 2000);
      return true;
    }
    return false;
  };

  const handleImageChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      // 显示本地预览
      const reader = new FileReader();
      reader.onloadend = () => {
        setPreviewUrl(reader.result as string);
      };
      reader.readAsDataURL(file);

      // 上传到服务器
      try {
        setIsUploading(true);
        const avatarUrl = await uploadAvatar(file);
        toast({
          title: '上传成功',
          description: '头像已更新',
        });
        // 更新预览URL为服务器返回的URL
        setPreviewUrl(avatarUrl || null);
      } catch (error: any) {
        console.error('头像上传错误:', error);
        
        // 处理认证错误
        if (!handleAuthError(error)) {
          toast({
            title: '上传失败',
            description: error.message || '请稍后重试',
            variant: 'destructive',
          });
          // 恢复原来的头像
          setPreviewUrl(user.avatar || null);
        }
      } finally {
        setIsUploading(false);
      }
    }
  };

  async function onSubmit(data: ProfileFormValues) {
    setIsLoading(true);
    try {
      const updatedUser = await updateUserProfile({
        name: data.name,
        email: data.email || '',
        phone: data.phone || '',
      });
      
      toast({
        title: '更新成功',
        description: '个人资料已更新',
      });
      
      // 如果需要，可以在这里更新全局用户状态
    } catch (error: any) {
      console.error('更新个人资料错误:', error);
      
      // 处理认证错误
      if (!handleAuthError(error)) {
        toast({
          title: '更新失败',
          description: error.message || '请稍后重试',
          variant: 'destructive',
        });
      }
    } finally {
      setIsLoading(false);
    }
  }

  return (
    <>
      <Toaster />
      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
          <div className="mb-6">
            <FormLabel className="block mb-2">头像</FormLabel>
            <div className="flex items-center gap-4">
              {previewUrl && (
                <img
                  src={previewUrl}
                  alt="头像预览"
                  className="w-20 h-20 rounded-full object-cover border-2 border-gray-200"
                />
              )}
              <div className="flex-1">
                <Input
                  type="file"
                  accept="image/*"
                  onChange={handleImageChange}
                  className="flex-1"
                  disabled={isUploading}
                />
                {isUploading && (
                  <p className="text-sm text-blue-500 mt-1">上传中...</p>
                )}
              </div>
            </div>
          </div>

          <FormField
            control={form.control}
            name="name"
            render={({ field }) => (
              <FormItem>
                <FormLabel>姓名</FormLabel>
                <FormControl>
                  <Input placeholder="请输入姓名" {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />

          <FormField
            control={form.control}
            name="email"
            render={({ field }) => (
              <FormItem>
                <FormLabel>邮箱（选填）</FormLabel>
                <FormControl>
                  <Input placeholder="请输入邮箱" type="email" {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />

          <FormField
            control={form.control}
            name="phone"
            render={({ field }) => (
              <FormItem>
                <FormLabel>手机号码（选填）</FormLabel>
                <FormControl>
                  <Input placeholder="请输入手机号码" {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />

          <Button type="submit" disabled={isLoading} className="w-full">
            {isLoading ? '保存中...' : '保存修改'}
          </Button>
        </form>
      </Form>
    </>
  );
} 